package us.versus.them.bitly;

import flash.display.BitmapData;

class Hough implements Bitter {

	var cosUP : Array< Float >;
	var sinUP : Array< Float >;

	public function new() {
	}

	public function reset( w:Int, h:Int, bitmapData:BitmapData, tmp:BitmapData ) : Void {
		App.clear( w, h, bitmapData, 0xFFFFFF );
		if ( null == cosUP ) {
			var theta_step =  Math.PI / w;
			cosUP = new Array< Float >();
			sinUP = new Array< Float >();
			var f = 0.0;
			for ( i in 0 ... w ) { 
				cosUP.push( Math.cos( f ) );
				sinUP.push( Math.sin( f ) );
				f += theta_step;
			}
		}
	}

	public function loop( w:Int, h:Int, bitmapData:BitmapData, tmp:BitmapData ) : Bool {
		var y = Math.random() * h;
		var z = Math.random() * h;
		var ydiff = ( z - y ) / w;
		var xskip = Math.floor( 1 + 10 * Math.random() + 20 * Math.random() );
		for ( x in 0 ... w ) {
			if ( 0 == x % xskip ) {
				hough( w, h, bitmapData, x, y );
			}
			y += ydiff;
		}

		return false;
	}

	public function hough( w:Int, h:Int, bitmapData:BitmapData, x:Float, y:Float ) {
		//bitmapData.setPixel( Math.floor( x ), Math.floor( y ), 0xFF00FF );
		var relx = x - w / 2;
		var rely = y - h / 2;
		for ( j in 0 ... w ) {
			var tmp = ( relx * cosUP[ j ] + rely * sinUP[ j ] );
			// move tmp from [ -h/2:h/2 ] to [ 0:h ]
			tmp += h / 2;

			// this should not happen, but it pays to be careful
			if ( tmp > -1 && tmp < h ) {
				var current = 1 + bitmapData.getPixel( j, Math.floor( tmp ) );
				bitmapData.setPixel( j, Math.floor( tmp ), current );
			}
		}
	} 
}
